﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HomePage.Controllers;
using TGVR_Boot;
using Telerik.Web.Mvc;
using PortalNews.BUS;
using System.Globalization;
using TGVR_Boot.DTO;
using PortalBooking;
using PortalBooking.BUS;
using PortalBooking.DAO;
using PortalTicket.DAO;
using System.Net.Mail;
using System.Net;
using System.Configuration;
using MDF.Worker;
using TGVR_Boot.Workers;
using MDF.Logger.Managements;
using Telerik.Web.Mvc.UI;
using MDF.Utilites.Helper;
using System.Web.SessionState;
using System.Threading.Tasks;
using System.Threading;
using DataHelper;
using TGVR_Report;

namespace TGVR_Project.Controllers
{
    public class FlightSearchController : BaseController
    {
        #region Flight Search
        //
        // GET: /FlightSearch/
        public ActionResult Index()
        {
            return Redirect("/");
        }

        private bool IsMemberLogined
        {
            get
            {
                return LoginUser.IsInRole("member");
            }
        }

        public string Detail()
        {
            string param = Request.QueryString.ToString();
            int iStart = param.IndexOf('=');
            param = param.Substring(iStart + 1, param.Length - iStart - 1);
            param = HttpUtility.UrlDecode(param);
            string url = "http://abay.vn/" + param;
            //Requester rq = new Requester();
            //var res = rq.GetData(url);
            //return rq.GetHtmlFromResponse(res);
            return "";
        }

        [HttpPost]
        public ActionResult Index(string fromcity, string tocity, string DatePickerDepartDate,
            string DatePickerReturnDate,
            int Adult, int Child, int Baby, bool IsFindCheapest = false)
        {
            try
            {
                LogManager.GetInstance().Info(string.Format("[{0}] Seach tickets", HttpContext.Request.UserHostAddress));
                NewsBUS nBUS = new NewsBUS();
                ViewBag.LatestNews = nBUS.GetlatestNews(m_lang.iLang, 4);

                DateTime dtDatePickerDepartDate = DateTime.ParseExact(DatePickerDepartDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                DateTime dtDatePickerReturnDate = DateTime.Now;

                if (!string.IsNullOrEmpty(DatePickerReturnDate) && Request.Form["ways"] == "2")
                {
                    dtDatePickerReturnDate = DateTime.ParseExact(DatePickerReturnDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    ViewData["DatePickerReturnDate"] = dtDatePickerReturnDate;
                    ViewBag.ways = 2;
                }
                else
                {
                    ViewBag.ways = 1;
                    ViewData["DatePickerReturnDate"] = null;
                }
                if (ViewBag.ways == 2)
                {
                    if (dtDatePickerDepartDate > dtDatePickerReturnDate)
                    {
                        m_Result.IsSuccess = -1;
                        m_Result.AddMessage(m_lang.DATENOTRIGHT);
                        return base.RedirectToHome();
                    }
                }

                if (fromcity == tocity)
                {
                    m_Result.IsSuccess = -1;
                    m_Result.AddMessage(m_lang.AIRPORTNOTRIGHT);
                    return base.RedirectToHome();
                }
                if (Adult < Baby)
                {
                    m_Result.IsSuccess = -1;
                    m_Result.AddMessage(m_lang.BABYTOMUCH);
                    return base.RedirectToHome();
                }


                ViewData["fromcity"] = fromcity.Trim();
                ViewData["tocity"] = tocity.Trim();
                ViewData["DatePickerDepartDate"] = dtDatePickerDepartDate;
                ViewData["Adult"] = Adult;
                ViewData["Child"] = Child;
                ViewData["Baby"] = Baby;


                ViewData["ajax"] = true;
                ViewData["scrolling"] = true;
                ViewData["paging"] = false;
                ViewData["filtering"] = true;
                ViewData["grouping"] = true;
                ViewData["sorting"] = true;
                ViewData["showFooter"] = true;

                ViewBag.Title = "Tim ve may bay gia re nhat " + m_seo.Title;
                string strKey = generateID();
                ViewBag.Key = strKey;
                FirmDAO fDAO = new FirmDAO();
                List<TK_Firm> fList = new List<TK_Firm>();
                TK_Firm f = new TK_Firm();
                f.Fullname = m_lang.ALL;
                f.Name = "";
                fList.Add(f);
                var tReult = fDAO.GetList();
                fList.AddRange(tReult);
                ViewBag.FirmList = fList;
                TicketDataContextDataContext context = new TicketDataContextDataContext();
                if (context.TK_Stations.Where(m => m.CountryID == 1 && (fromcity.ToLower().IndexOf(m.Code.ToLower()) > -1
                    || tocity.ToLower().IndexOf(m.Code.ToLower()) > -1)
                    ).Count() == 2)
                {
                    ViewBag.IsInter = false;
                }
                else
                {
                    ViewBag.IsInter = true;
                }
                IsFindCheapest = Request.Form.GetValues("IsFindCheapest") != null;


                if (IsFindCheapest)
                {
                    //chuyển sang trang tìm vé rẻ trong tháng

                    ViewBag.Stack = false;
                    ViewBag.SeriesType = "line";
                    ViewBag.ShowTitle = true;
                    ViewBag.ShowLegend = true;
                    ViewBag.LegendPosition = ChartLegendPosition.Bottom;
                    ViewBag.IsSearchCheapest = IsFindCheapest;
                    return View("Cheapest");
                }
                LogManager.GetInstance().Info(string.Format("Search: {0} {1} {2} {3}", fromcity, tocity, dtDatePickerDepartDate, dtDatePickerReturnDate));
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi tìm vé", ex);
            }
            return View();
        }
        [GridAction]
        public ActionResult _ListResultIn(string SessionID, string fromcity, string tocity, DateTime DatePickerDepartDate,
            DateTime? DatePickerReturnDate, int Adult, int Child, int Baby, int iPage = 0, string airline = "")
        {

            _ListResultOut(SessionID, fromcity, tocity, DatePickerDepartDate,
             DatePickerReturnDate, Adult, Child, Baby, iPage, airline);

            return View(new GridModel(m_lstResult.Where(m => m.TypeWay.ToLower() == "in").OrderBy(m => m.Price)));
        }

        public ActionResult _ListResultInMobile(string SessionID, string fromcity, string tocity, DateTime DatePickerDepartDate,
       DateTime? DatePickerReturnDate, int Adult, int Child, int Baby, int iPage = 0, string airline = "")
        {
            _ListResultOutMobile(SessionID, fromcity, tocity, DatePickerDepartDate,
             DatePickerReturnDate, Adult, Child, Baby, iPage, airline);

            return PartialView("_ResultSearchPartialReturn", m_lstResult);
            //return View(new GridModel(m_lstResult.Where(m => m.TypeWay.ToLower() == "in").OrderBy(m => m.Price)));
        }

        [GridAction]
        public ActionResult _ListResultOut(string SessionID, string fromcity, string tocity,
            DateTime DatePickerDepartDate,
            DateTime? DatePickerReturnDate, int Adult, int Child, int Baby, int iPage = 0, string airline = "")
        {
            try
            {


                int iStart = fromcity.IndexOf('(');
                int iEnd = fromcity.IndexOf(')');

                string fromcityCode = fromcity.Substring(iStart + 1, iEnd - iStart - 1);

                iStart = tocity.IndexOf('(');
                iEnd = tocity.IndexOf(')');

                string tocityCode = tocity.Substring(iStart + 1, iEnd - iStart - 1);

                List<TicketDTO> lstTemp = new List<TicketDTO>();
                TicketDataContextDataContext context = new TicketDataContextDataContext();
                if (context.TK_Stations.Where(m => m.CountryID == 1 && (m.Code.ToLower() == fromcityCode.ToLower()
                    || m.Code.ToLower() == tocityCode.ToLower())
                    ).Count() == 2)
                {
                    #region Tìm vé trong nước
                    WorkerManager wkBus = new WorkerManager();
                    lstTemp.Clear();
                    wkBus.Add(new SearchTicketWorker("VietJetBootSeach", new VietJetBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, false, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("JetstarBootSeach", new JetstarBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, false, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("VietNamAirlineSeach", new VietNamAirline(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, false, IsMemberLogined));

                    wkBus.Run();

                    lstTemp.AddRange(m_lstResult);

                    #endregion
                }
                else
                {
                    #region Tìm vé quốc tế
                    WorkerManager wkBus = new WorkerManager();
                    lstTemp.Clear();
                    wkBus.Add(new SearchTicketWorker("AirAsianBootSeach", new AirAsianBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, true, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("JetstarBootSeach", new JetstarBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, true, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("VietNamAirlineSeach", new VietNamAirline(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, true, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("VietJetBootSeach", new VietJetBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, true, IsMemberLogined));

                    wkBus.Run();
                    lstTemp.AddRange(m_lstResult);
                    #endregion


                }

                Dictionary<string, object> Dictionary = new Dictionary<string, object>();
                if (Session[SessionID] != null)
                    Dictionary = (Dictionary<string, object>)Session[SessionID];

                Dictionary["fromcity"] = fromcity;
                Dictionary["tocity"] = tocity;
                Dictionary["DatePickerDepartDate"] = DatePickerDepartDate;
                Dictionary["DatePickerReturnDate"] = DatePickerReturnDate;
                Dictionary["Adult"] = Adult;
                Dictionary["Child"] = Child;
                Dictionary["Baby"] = Baby;
                Dictionary["Airline"] = airline;
                Dictionary["result"] = lstTemp;
                if (Session[SessionID] == null)
                    Session.Add(SessionID, Dictionary);
                else
                    Session[SessionID] = Dictionary;
                return View(new GridModel(lstTemp.Where(m => m.TypeWay.ToLower() == "out").OrderBy(m => m.Price)));
            }

            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi tìm vé", ex);
            }
            return null;
        }


        #region ndphu
        [AllowAnonymous]
        public ActionResult _ListResultOutMobile(string SessionID, string fromcity, string tocity,
     DateTime DatePickerDepartDate,
     DateTime? DatePickerReturnDate, int Adult, int Child, int Baby, int iPage = 0, string airline = "")
        {
            List<TicketDTO> lstTemp = new List<TicketDTO>();
            try
            {


                int iStart = fromcity.IndexOf('(');
                int iEnd = fromcity.IndexOf(')');

                string fromcityCode = fromcity.Substring(iStart + 1, iEnd - iStart - 1);

                iStart = tocity.IndexOf('(');
                iEnd = tocity.IndexOf(')');

                string tocityCode = tocity.Substring(iStart + 1, iEnd - iStart - 1);


                TicketDataContextDataContext context = new TicketDataContextDataContext();
                if (context.TK_Stations.Where(m => m.CountryID == 1 && (m.Code.ToLower() == fromcityCode.ToLower()
                    || m.Code.ToLower() == tocityCode.ToLower())
                    ).Count() == 2)
                {
                    #region Tìm vé trong nước
                    WorkerManager wkBus = new WorkerManager();
                    lstTemp.Clear();
                    wkBus.Add(new SearchTicketWorker("VietJetBootSeach", new VietJetBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, false, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("JetstarBootSeach", new JetstarBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, false, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("VietNamAirlineSeach", new VietNamAirline(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, false, IsMemberLogined));

                    wkBus.Run();

                    lstTemp.AddRange(m_lstResult);

                    #endregion
                }
                else
                {
                    #region Tìm vé quốc tế
                    WorkerManager wkBus = new WorkerManager();
                    lstTemp.Clear();
                    wkBus.Add(new SearchTicketWorker("AirAsianBootSeach", new AirAsianBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, true, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("JetstarBootSeach", new JetstarBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, true, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("VietNamAirlineSeach", new VietNamAirline(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, true, IsMemberLogined));
                    wkBus.Add(new SearchTicketWorker("VietJetBootSeach", new VietJetBoot(), ComineTickets, fromcityCode, tocityCode, DatePickerDepartDate, DatePickerReturnDate, Adult, Child, Baby, true, IsMemberLogined));

                    wkBus.Run();
                    lstTemp.AddRange(m_lstResult);
                    #endregion


                }

                Dictionary<string, object> Dictionary = new Dictionary<string, object>();
                if (Session[SessionID] != null)
                    Dictionary = (Dictionary<string, object>)Session[SessionID];

                Dictionary["fromcity"] = fromcity;
                Dictionary["tocity"] = tocity;
                Dictionary["DatePickerDepartDate"] = DatePickerDepartDate;
                Dictionary["DatePickerReturnDate"] = DatePickerReturnDate;
                Dictionary["Adult"] = Adult;
                Dictionary["Child"] = Child;
                Dictionary["Baby"] = Baby;
                Dictionary["Airline"] = airline;
                Dictionary["result"] = lstTemp;
                if (Session[SessionID] == null)
                    Session.Add(SessionID, Dictionary);
                else
                    Session[SessionID] = Dictionary;

                //return Json("result",JsonRequestBehavior.AllowGet);
            }

            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi tìm vé", ex);
            }
            //var result = lstTemp.Where(m => m.TypeWay.ToLower() == "out").OrderBy(m => m.Price).Select(m => m.From).ToList();

            return PartialView("_ResultSearchPartial", lstTemp);
        }

        #endregion

        private List<TicketDTO> m_lstResult = new List<TicketDTO>();

        private void ComineTickets(object data)
        {
            try
            {
                if (data != null)
                    this.m_lstResult.AddRange((List<TicketDTO>)data);
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Home Seach ticket: Lỗi tìm vé rẻ trong tháng", ex);
            }
        }
        #endregion

        #region Booking
        public ActionResult Booking(string SessionID, string DepartTicket, string ReturnTicket)
        {
            LogManager.GetInstance().Info(string.Format("[{0}] booking", HttpContext.Request.UserHostAddress));
            try
            {
                if (Session[SessionID] == null)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage(m_lang.SESSIONTIMEOUT);
                    return RedirectToHome();
                }

                Dictionary<string, object> Dictionary = (Dictionary<string, object>)Session[SessionID];
                if (Dictionary["result"] == null)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage(m_lang.LOSERESULT);
                    return RedirectToHome();
                }
                List<TicketDTO> lst = (List<TicketDTO>)Dictionary["result"];
                var rtDepart = lst.Where(m => m.FlightNo == DepartTicket);
                if (rtDepart == null || rtDepart.Count() == 0)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage(m_lang.NODEPARTSELETED);
                    return RedirectToHome();
                }
                TicketDTO tDepart = rtDepart.SingleOrDefault();
                TicketDTO tReturn = null;
                var rtReturn = lst.Where(m => m.FlightNo == ReturnTicket);
                if (rtDepart != null && rtDepart.Count() > 0)
                {
                    tReturn = rtReturn.SingleOrDefault();
                }
                if (!Dictionary.Keys.Contains("tDepart"))
                {
                    Dictionary.Add("tDepart", tDepart);
                    Dictionary.Add("tReturn", tReturn);
                    Dictionary.Add("PaymentType", Request.Form["PaymentType"]);
                }
                ViewBag.SessionID = SessionID;
                ViewBag.tDepart = tDepart;
                ViewBag.tReturn = tReturn;
                ViewBag.fromcity = Dictionary["fromcity"];
                ViewBag.tocity = Dictionary["tocity"];
                ViewBag.DatePickerDepartDate = Dictionary["DatePickerDepartDate"];
                ViewBag.DatePickerReturnDate = Dictionary["DatePickerReturnDate"];
                ViewBag.Adult = Dictionary["Adult"];
                ViewBag.Child = Dictionary["Child"];
                ViewBag.Baby = Dictionary["Baby"];
                ViewBag.PaymentType = Request.Form["PaymentType"];
                ViewData["Adult"] = Dictionary["Adult"];
                ViewData["Child"] = Dictionary["Child"];
                ViewData["Baby"] = Dictionary["Baby"];
                ViewBag.ways = Dictionary["DatePickerReturnDate"] == null ? 1 : 2;
                ViewData["Ways"] = ViewBag.ways;
                List<TicketDTO> lstTicket = new List<TicketDTO>();
                if (tDepart != null)
                {
                    lstTicket.Add(tDepart);
                    if (tDepart.DateStart < DateTime.Now.AddDays(2))// <48
                    {
                        SettingDAO setting = new SettingDAO();
                        ViewBag.FeeService = Int32.Parse(setting.GetSetting("FeeServiceAsia"));
                    }
                    else
                    {

                    }
                }
                if (tReturn != null)
                    lstTicket.Add(tReturn);

                return View(lstTicket);
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi đặt vé", ex);
                return View();
            }
        }

        public ActionResult CheckOut(BK_Passenger[] Passenger, BK_Booking Booking)
        {
            LogManager.GetInstance().Info(string.Format("[{0}] checkout", HttpContext.Request.UserHostAddress));
            try
            {
                if (Session[Booking.SessionID] == null)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage(m_lang.SESSIONTIMEOUT);
                    return RedirectToHome();
                }

                if (Passenger.Count(m => m.TypeID == 1) < Passenger.Count(m => m.TypeID == 3))
                {
                    return null;
                }

                for (int i = 0; i < Passenger.Length; i++)
                {
                    var temp = Request.Form["Birthday_"+i];
                    Passenger[i].Birthday = DateTime.ParseExact(temp, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    Passenger[i].Email = Booking.Email;
                    Passenger[i].Phone = Booking.Phone;

                    Passenger[i].Address = StringHelper.ToNonUnicode(Passenger[i].Address);
                    Passenger[i].City = StringHelper.ToNonUnicode(Passenger[i].City);
                    //Passenger[i].Email = StringHelper.ToNonUnicode(Passenger[i].Email);
                    Passenger[i].FirstName = StringHelper.ToNonUnicode(Passenger[i].FirstName).ToUpper();
                    Passenger[i].Name = StringHelper.ToNonUnicode(Passenger[i].Name).ToUpper();
                }
                Booking.Name = StringHelper.ToNonUnicode(Booking.Name).ToUpper();

                Dictionary<string, object> Dictionary = (Dictionary<string, object>)Session[Booking.SessionID];
                if (Dictionary["result"] == null)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage(m_lang.LOSERESULT);
                    return RedirectToHome();
                }
                TicketDTO tDepart = (TicketDTO)Dictionary["tDepart"];
                TicketDTO tReturn = (TicketDTO)Dictionary["tReturn"];

                if (tReturn != null && tDepart.DateStart >= tReturn.DateStart)
                {
                    return null;
                }

                BookingBUS bBUS = new BookingBUS();
                Booking.IP = Request.UserHostAddress;
                if (LoginUser.INFO != null)
                    Booking.UserId = LoginUser.INFO.UserId;
                #region Get Payment Type
                string strPayment = "1";
                if (Dictionary["PaymentType"] != null)
                    strPayment = Dictionary["PaymentType"].ToString();

                Booking.PaymentTypeID = Int32.Parse(strPayment);
                int iPaymentType = 1;
                if (Int32.TryParse(strPayment, out iPaymentType))
                {
                    Booking.PaymentTypeID = iPaymentType;
                }
                #endregion
                BK_Booking bk = bBUS.CreateBooking(Booking, Passenger, tDepart, tReturn, IsMemberLogined);

                if (bk == null)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage(m_lang.CREATEBOOKINGFAIL + ": 2");
                    return RedirectToHome();
                }
                if (bk.Status < 0)
                {
                    this.m_Result.IsSuccess = -1;
                    switch (bk.Status)
                    {
                        case (int)BookingStatus.CANTFINDWAYS:
                            this.m_Result.AddMessage(m_lang.CANTFINDWAYS);
                            break;
                        case (int)BookingStatus.CHANGEDPRICE:
                            this.m_Result.AddMessage(m_lang.CHANGEDPRICE);
                            break;
                        case (int)BookingStatus.FINDWRONGDATE:
                            this.m_Result.AddMessage(m_lang.FINDWRONGDATE);
                            break;
                        case (int)BookingStatus.NORESULTFIND:
                            this.m_Result.AddMessage(m_lang.NORESULTFIND);
                            break;
                        case (int)BookingStatus.NOTHAVEBABIESEAT:
                            this.m_Result.AddMessage(m_lang.NOTHAVEBABIESEAT);
                            break;
                        case (int)BookingStatus.NOTLOGIN:
                            this.m_Result.AddMessage(m_lang.NOTLOGIN);
                            break;
                        case (int)BookingStatus.NOTMACTHDEPART:
                            this.m_Result.AddMessage(m_lang.NOTMACTHDEPART);
                            break;
                        case (int)BookingStatus.NOTMACTHRETURN:
                            this.m_Result.AddMessage(m_lang.NOTMACTHRETURN);
                            break;
                        case (int)BookingStatus.OUTOFBOOKING:
                            this.m_Result.AddMessage(m_lang.OUTOFBOOKING);
                            break;
                        case (int)BookingStatus.SERVERBUSY:
                            this.m_Result.AddMessage(m_lang.SERVERBUSY);
                            break;
                        case (int)BookingStatus.UNKNOW:
                            this.m_Result.AddMessage(m_lang.UNKNOW);
                            break;
                        case (int)BookingStatus.HOTSEAT:
                            this.m_Result.AddMessage(m_lang.HOTSEAT);
                            break;
                        case (int)BookingStatus.PAYNOW:
                            this.m_Result.AddMessage(m_lang.PAYNOW);
                            break;
                        default:
                            this.m_Result.AddMessage(m_lang.CHANGEDPRICE);
                            break;
                    }

                    return View();
                }
                else
                {
                    Session[Booking.SessionID] = null;
                    string Content = "";

                    try
                    {
                        #region Mail message

                        string strTickets = "<br><br><table class='info' border='1px solid black'>" +
                "<tr><th>Tên hành khách</th><th>Mã chuyến bay</th><th>Nơi đi</th><th>Nơi đến</th><th>Giờ bay</th><th>Giá vé</th></tr>";
                        string strFooter = "<br><br><img src='http://thegioivere.net/bank.jpg'/>";
                        BookingDetailDAO bkdDAO = new BookingDetailDAO();
                        var lstDetailBooking = bkdDAO.Get(Booking.ID);
                        foreach (var item in lstDetailBooking)
                        {
                            strTickets += string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td></tr>",
                                item.BK_Passenger.FirstName + " " + item.BK_Passenger.Name + (item.BK_Passenger.TypeID == 2 ? " CHD" : "") + (item.BK_Passenger.TypeID == 3 ? " INF" : ""),
                                item.FlightNo,
                                item.FromCity,
                                item.ToCity,
                                item.StartDate.ToString("dd/MM/yyyy HH:mm") + " " + (((tDepart.FlightNo.Replace(" ", "").ToLower() == item.FlightNo.Replace(" ", "").ToLower()) || (tReturn == null)) ? tDepart.DateEnd.ToString("dd/MM/yyyy HH:mm") : tReturn.DateEnd.ToString("dd/MM/yyyy HH:mm")),
                                item.Price.ToString("#,##0") + " vnđ"
                                );
                        }
                        strTickets += string.Format("</table><br>");

                        Content = "<html><body>" +
            "<div style='color:white;font-weight:bold;background-color:rgb(255,102,0);text-align:center;padding:10px;font-size:30px'>ĐẶT VÉ THÀNH CÔNG TẠI THẾ GIỚI VÉ RẺ</div>" +
            "<div><br>" +
            "<br>Kính gửi quý khách: <label style='text-transform:uppercase'>" + Booking.Name + "</label><br>" +
            "<br><br>I.Thông tin đặt vé:<br>" +
            "   1. Người đặt vé:" + Booking.Name.Trim() + "<br/>" +
            "   2. Số điện thoại:" + Booking.Phone + "<br/>" +
            "   3. Email:" + Booking.Email + "<br/>" +
            "   4. Địa chỉ:" + Booking.Address + "<br/>" +
            "   5. Ngày đặt: " + Booking.CreatedDate.ToString("dd/MM/yyyy") + "<br>" +
            "   6. Mã đặt vé: <b style='color:red;font-size:22px'>" + (Booking.Status > 0 ? Booking.rCode : "Vui lòng liên hệ ") +
            ((Booking.Status == (int)BookingStatus.PAYNOW) ? "(Vé đi ngay cần thanh toán ngay)" : "") +
            ((Booking.Status == (int)BookingStatus.HOTSEAT) ? "(Vé khuyến mãi cần thanh toán ngay)" : "") +
            "   <br>7. Tình trạng vé: Chờ thanh toán <br/>" +
            " </b><br>" +
            "<br/><br>II. Thông tin chuyến bay" +
            "<style>.info th{padding: 3px;}</style>" +
            strTickets +
            "<br>III. Tổng tiền cần thanh toán: <b style='color:red;font-size:22px'>" + lstDetailBooking.Sum(m => m.Price).ToString("#,##0") +
              "</b><br><br>" +
               "<br>* <b style='color:#000000;font-size:18px'>Khi chuyển khoản vui lòng khi rõ: thanh toán tiền vé MB cho mã code: " + (Booking.Status > 0 ? Booking.rCode : "") + "</b><br>" +
               "<br>Vui lòng thanh toán trước " + DateTime.Now.AddDays(1).ToString("dd/MM/yyyy HH:mm") + " sau thời hạn trên vé sẽ bị hủy" +
               "<br>Booking này sẽ giữ chỗ dự kiến được trong vòng 24h kể từ " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + " và phải đảm bảo cách ngày bay đầu tiên trên vé tối thiểu 24h." +
              "<br>The booking created by <a href='http://thegioivere.net/'>thegioviere.net</a>" +
              "<br><b style='font-size:18px'>Cảm ơn quý khách đã đặt vé tại Thegioivere.net</b>" +
              strFooter +
            "</div>" +
        "</body></html>";
                        //Cảm ơn quý khách đã đặt vé tại Thegioivere.net
                        /*End Mail message*/

                        this.SendMail(Booking.Email, "[TheGioiVeRe.Net] - THÔNG BÁO ĐẶT VÉ", Content);

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        LogManager.GetInstance().Error("Lỗi gửi mail", ex);
                    }

                    this.m_Result.IsSuccess = Booking.Status;
                    if (Booking.Status == (int)BookingStatus.HOTSEAT)
                    {
                        this.m_Result.AddMessage(m_lang.HOTSEAT);
                    }

                    if (Booking.Status == (int)BookingStatus.PAYNOW)
                    {
                        this.m_Result.AddMessage("Đây là vé đi ngay, bạn cần thanh toán trực tiếp với TGVR");
                    }
                    this.m_Result.AddMessage(m_lang.CHECKMAIL + "(" + Booking.Email + ")");
                    string strUsers = "";

                    foreach (var item in Passenger)
                    {
                        strUsers += item.FirstName + " " + item.Name + "<br>";
                    }

                    if (Booking.Status > 0)
                    {
                        string strMess = string.Format("Code: {0}<br>" +
                                "{1}" +
                                "{2} {3} {4} {5} {6}<br>" +
                                "{7}{8}{9}{10}{11}" +
                                "Hanh ly xach tay: {12}<br>" +
                                "Hanh ly ky gui: {13}<br>" +
                                "Vui long den som truoc 90p<br>" +
                                "Gia ve: {14}",
                                Booking.rCode.Replace(" ", ""),//0
                                strUsers,

                                tDepart.FlightNo,//2
                                tDepart.From,//3
                                tDepart.To,//4
                                tDepart.DateStart.ToString("dd/MM"),//5
                                tDepart.DateStart.ToString("HH:mm"),//6

                                tReturn != null ? tReturn.FlightNo + " " : "",//7
                                tReturn != null ? tReturn.From + " " : "",//8
                                tReturn != null ? tReturn.To + " " : "",//9
                                tReturn != null ? tReturn.DateStart.ToString("dd/MM") + " " : "",//10
                                tReturn != null ? tReturn.DateStart.ToString("HH:mm") + "<br>" : "",//11

                                "7kg",//12
                                tReturn == null ? (tDepart.FlightNo.Substring(0, 2).ToLower() == "vn" ? "20kg" : "0kg") : (tDepart.FlightNo.Substring(0, 2).ToLower() == "vn" ? "20kg" : "0kg") + "-" + (tReturn.FlightNo.Substring(0, 2).ToLower() == "vn" ? "20kg" : "0kg"),//13
                                Booking.TotalPrice.ToString("#,##0")//14
                        );
                        //var arrTemp = strMess.Replace("<br>", "_").Split('_');
                        //foreach (var item in arrTemp)
                        //{
                        this.m_Result.AddMessage(strMess);
                        if (Booking.Status == 1)
                        {
                            string ticket = string.Format("Lưu vé & kiểm tra vé <a style='color:blue' href='/FlightSearch/GetTicket/{0}'>Click here</a>",
                                Booking.rCode);
                            this.m_Result.AddMessage(ticket);
                        }
                        //}



                    }
                    return View();
                    //return RedirectToHome();

                }
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi đặt vé", ex);
                return RedirectToHome();
            }
        }
        #endregion

        #region Order ticket
        public ActionResult OrderTicket(string id)
        {
            LogManager.GetInstance().Info(string.Format("[{0}] order", HttpContext.Request.UserHostAddress));
            try
            {
                if (Session[id] == null)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage(m_lang.SESSIONTIMEOUT + ": 0");
                    return RedirectToHome();
                }

                Dictionary<string, object> Dictionary = (Dictionary<string, object>)Session[id];

                ViewBag.strDate = ((DateTime)Dictionary["DatePickerDepartDate"]).ToString("dd/MM/yyyy");
                ViewBag.strFrom = Dictionary["fromcity"].ToString();
                ViewBag.strTo = Dictionary["tocity"].ToString();
                return View("OrderTicket");
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi yêu cầu đặt vé", ex);
                return View("OrderTicket");
            }
        }
        [HttpPost]
        public ActionResult OrderTicket(BK_Order Order)
        {
            LogManager.GetInstance().Info(string.Format("[{0}] save order", HttpContext.Request.UserHostAddress));
            try
            {
                OrderDAO oDAO = new OrderDAO();
                if (oDAO.Insert(Order))
                {
                    this.SendMail(null, "Yêu cầu đặt vé", Order.Note);
                    this.m_Result.IsSuccess = 1;
                    this.m_Result.AddMessage(m_lang.SUCCESS);
                    return RedirectToHome();
                }
                return View("OrderTicket");
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi yêu cầu đặt vé", ex);
                return View("OrderTicket");
            }
        }
        #endregion

        #region Utils
        private string generateID()
        {
            try
            {
                long i = 1;

                foreach (byte b in Guid.NewGuid().ToByteArray())
                {
                    i *= ((int)b + 1);
                }

                string number = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 1000000000);

                return number;
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi tạo SessionID", ex);
                return "";
            }
        }

        //Satrt Send Email Function
        public void SendMail(string toList,
            string subject, string body)
        {
            LogManager.GetInstance().Info(string.Format("[{0}] Send mail", HttpContext.Request.UserHostAddress));
            if (ConfigurationManager.AppSettings["MailAddress"] != null && ConfigurationManager.AppSettings["Password"] != null)
            {
                string strMailAddress = ConfigurationManager.AppSettings["MailAddress"].ToString();
                string strPassword = ConfigurationManager.AppSettings["Password"].ToString();
                string strCCList = ConfigurationManager.AppSettings["CCList"].ToString();
                MailMessage message = new MailMessage();
                SmtpClient smtpClient = new SmtpClient();
                string msg = string.Empty;
                try
                {
                    MailAddress fromAddress = new MailAddress(strMailAddress);
                    message.From = fromAddress;
                    message.To.Add(toList);
                    if (strCCList != null && strCCList != string.Empty)
                        message.CC.Add(strCCList);
                    if (toList == null)
                    {
                        toList = strCCList;
                        message.CC.Clear();
                    }
                    message.Subject = subject;
                    message.IsBodyHtml = true;
                    message.Body = body;
                    // We use gmail as our smtp client
                    smtpClient.Host = "smtp.gmail.com";
                    smtpClient.Port = 587;
                    smtpClient.EnableSsl = true;
                    smtpClient.UseDefaultCredentials = true;
                    smtpClient.Credentials = new System.Net.NetworkCredential(
                        strMailAddress, strPassword);
                    //Gia su chay thanh cong
                    //smtpClient.Send(message);
                    msg = "Successful<BR>";
                }
                catch (Exception ex)
                {
                    LogManager.GetInstance().Error("Send mail have a problem", ex);
                }
            }

        }
        //End Send Email Function
        #endregion

        #region Report tickets
        public ActionResult GetTicket(string id)
        {
            if (string.IsNullOrEmpty(id))
                return null;
            BookingDAO bookDAO = new BookingDAO();
            BK_Booking book = bookDAO.Get(id);
            if (book == null)
            {
                m_Result.IsSuccess = -1;
                m_Result.AddMessage("Get ticket error!");
                LogManager.GetInstance().Error("Get ticket error!");
                return RedirectToHome();
            }
            if (id.IndexOf('-') > -1 && id.Split('-').Length != 2)
            {
                m_Result.IsSuccess = -1;
                m_Result.AddMessage("Code ticket error!");
                LogManager.GetInstance().Error("Code ticket error! " + id);
                return RedirectToHome();
            }


            IReport r = new VietJetTicket(id);
            byte[] contents = r.GetReportToBytes();
            return File(contents, "application/pdf", string.Format("{0}-{1}-{2}-{3}.pdf",
                book.CreatedDate.ToString("dd/MM/yyyy"),//0
                id,//1
                book.Name,//2
                book.FromCity + book.ToCity//3
                ));
        }
        #endregion

        public ActionResult TicketNational()
        {
            return View();
        }
        [HttpPost]
        public ActionResult TicketNationalResult(string fromcity, string tocity, string DatePickerDepartDate,
            string DatePickerReturnDate,
            int Adult, int Child, int Baby, bool IsFindCheapest = false)
        {
            try
            {
                LogManager.GetInstance().Info(string.Format("[{0}] Seach tickets", HttpContext.Request.UserHostAddress));
                NewsBUS nBUS = new NewsBUS();
                ViewBag.LatestNews = nBUS.GetlatestNews(m_lang.iLang, 4);

                DateTime dtDatePickerDepartDate = DateTime.ParseExact(DatePickerDepartDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                DateTime dtDatePickerReturnDate = DateTime.Now;

                if (!string.IsNullOrEmpty(DatePickerReturnDate) && Request.Form["ways"] == "2")
                {
                    dtDatePickerReturnDate = DateTime.ParseExact(DatePickerReturnDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    ViewData["DatePickerReturnDate"] = dtDatePickerReturnDate;
                    ViewBag.ways = 2;
                }
                else
                {
                    ViewBag.ways = 1;
                    ViewData["DatePickerReturnDate"] = null;
                }
                if (ViewBag.ways == 2)
                {
                    if (dtDatePickerDepartDate > dtDatePickerReturnDate)
                    {
                        m_Result.IsSuccess = -1;
                        m_Result.AddMessage(m_lang.DATENOTRIGHT);
                        return base.RedirectToHome();
                    }
                }

                if (fromcity == tocity)
                {
                    m_Result.IsSuccess = -1;
                    m_Result.AddMessage(m_lang.AIRPORTNOTRIGHT);
                    return base.RedirectToHome();
                }
                if (Adult < Baby)
                {
                    m_Result.IsSuccess = -1;
                    m_Result.AddMessage(m_lang.BABYTOMUCH);
                    return base.RedirectToHome();
                }


                ViewData["fromcity"] = fromcity.Trim();
                ViewData["tocity"] = tocity.Trim();
                ViewData["DatePickerDepartDate"] = dtDatePickerDepartDate;
                ViewData["Adult"] = Adult;
                ViewData["Child"] = Child;
                ViewData["Baby"] = Baby;


                ViewData["ajax"] = true;
                ViewData["scrolling"] = true;
                ViewData["paging"] = false;
                ViewData["filtering"] = true;
                ViewData["grouping"] = true;
                ViewData["sorting"] = true;
                ViewData["showFooter"] = true;

                ViewBag.Title = "Tim ve may bay gia re nhat " + m_seo.Title;
                string strKey = generateID();
                ViewBag.Key = strKey;
                FirmDAO fDAO = new FirmDAO();
                List<TK_Firm> fList = new List<TK_Firm>();
                TK_Firm f = new TK_Firm();
                f.Fullname = m_lang.ALL;
                f.Name = "";
                fList.Add(f);
                var tReult = fDAO.GetList();
                fList.AddRange(tReult);
                ViewBag.FirmList = fList;
                TicketDataContextDataContext context = new TicketDataContextDataContext();
                if (context.TK_Stations.Where(m => m.CountryID == 1 && (fromcity.ToLower().IndexOf(m.Code.ToLower()) > -1
                    || tocity.ToLower().IndexOf(m.Code.ToLower()) > -1)
                    ).Count() == 2)
                {
                    ViewBag.IsInter = false;
                }
                else
                {
                    ViewBag.IsInter = true;
                }
                IsFindCheapest = Request.Form.GetValues("IsFindCheapest") != null;


                if (IsFindCheapest)
                {
                    //chuyển sang trang tìm vé rẻ trong tháng

                    ViewBag.Stack = false;
                    ViewBag.SeriesType = "line";
                    ViewBag.ShowTitle = true;
                    ViewBag.ShowLegend = true;
                    ViewBag.LegendPosition = ChartLegendPosition.Bottom;
                    ViewBag.IsSearchCheapest = IsFindCheapest;
                    return View("Cheapest");
                }
                LogManager.GetInstance().Info(string.Format("Search: {0} {1} {2} {3}", fromcity, tocity, dtDatePickerDepartDate, dtDatePickerReturnDate));
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Lỗi tìm vé", ex);
            }
            return View();
        }

        public JsonResult GetAllAirport()
        {
            PortalTicket.BUS.StationBUS sBus = new PortalTicket.BUS.StationBUS();
            var data = sBus.GetAllName();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}
